<?php

namespace app\common\service;
use think\Db;

class BalanceService{
	
	/**
	 * [更新资产]
	 * @param  [type] $uid    [description]
	 * @param  [type] $wid    [变动钱包]
	 * @param  [type] $amount [变动数量]
	 * @param  [type] $remark [变动原因]
	 * @return [type]         [变动类型]
	 */
	public static function updateBalance($uid,$wid,$amount,$remark,$type=1,$order_id=0,$order_remark=''){
		if($amount == 0){
			return false;
		}
		
		Db::startTrans();
		if ($wid == 1 || $wid == 10) {
			if ($amount < 0) {
				$data = Db::table('tp_invest_record')->where('uid',$uid)->where('status',2)->find();
				if ($data) {
					$config = Db::table('tp_invest_config')->where('id',$data['config_id'])->find();
					$balance = Db::table('tp_user_balance')->where('uid',$uid)->where('wid',1)->value('balance');
    				$ty_balance = Db::table('tp_user_balance')->where('uid',$uid)->where('wid',10)->value('balance');
    				$user_balance = $balance + $ty_balance - abs($amount);
					if ($user_balance < $config['min']) {
				        Db::table('tp_invest_record')->where('id',$data['id'])->update([
				          'status'=>1,
				          'close_type'=>1,
				          'close_date'=>date('Y-m-d H:i:s')
				        ]);
				    }
				}
			}
		}
		//更新余额
		$res1 = model('UserBalanceModel')->updateBalance($uid, $wid, $amount);
		//插入记录
		$res2 = model('BalanceRecordModel')->addRecord($uid, $wid, $amount, $remark, $type,$order_id,$order_remark);
		if ($res1 && $res2) {
			Db::commit();
			return true;
		} else {
			Db::rollback();
			return false;
		}
	}
	
	/*
	资金修正
	 */
	public static function repairBalance(){
		
	}
}